# -*- coding:utf-8 -*-
# import tornado
from re import DEBUG
import tornado.ioloop
import tornado.web
import jieba
import json
import sql_service
from sql_service import DBService

from urllib import parse,request

class CutStringService(object):
    def __init__(self):
        self.cache = {}

    def cutString(self,dataStr):
        seg_list = list(jieba.cut(dataStr, cut_all=False))
        # print("Default Mode: " + " ".join(seg_list))  # 精确模式
        return seg_list

class CutStringHandler(tornado.web.RequestHandler):
    service = CutStringService()

    def get(self):
        dataStr = (self.get_argument("jiebaStr")).encode("UTF-8")
        resStr = self.service.cutString(dataStr)
        result = {
            "status": '200',
            "dataStr": resStr
        }
        try:
            self.write(json.dumps(result))
        except:
            self.write('status:501'+str(type(resStr)))

class CityCodeService(object):
    def __init__(self):
        self.cache = {}

    def getCityCodeByName(self,dataStr):
        db = DBService()
        result = db.select('city_name',dataStr,'city_cma')
        return result

class CityCodeHandler(tornado.web.RequestHandler):
    service = CityCodeService()

    def get(self):
        dataStr = (self.get_argument("city")).encode("UTF-8")
        dataStr = dataStr.decode("utf-8")
        # print(dataStr) # dataStr == (('北京', '101010100'),)
        resStr = self.service.getCityCodeByName(dataStr)[0]
        result = {
            "status": '200',
            "dataStr": resStr
        }
        try:
            self.write(json.dumps(result))
        except:
            self.write('status:501'+str(type(resStr)))

class WeatherService(object):
    def __init__(self):
        self.cache = {}

    def getWeatherByCityCode(self,dataStr):
        print(dataStr[1])
        header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'}
        url = 'http://t.weather.itboy.net/api/weather/city/'
        req = request.Request(url='%s%s' % (url,dataStr[1]),headers=header_dict)
        result = request.urlopen(req)
        result = result.read().decode(encoding='utf-8')
        return result

class WeatherHandler(tornado.web.RequestHandler):
    service = WeatherService()
    city = CityCodeService()

    def get(self):
        # 获取cityCode
        dataStr = (self.get_argument("city")).encode("UTF-8")
        dataStr = dataStr.decode("utf-8")
        resStr = self.city.getCityCodeByName(dataStr)[0]

        resStr = self.service.getWeatherByCityCode(resStr)
        result = {
            "status": '200',
            "dataStr": resStr
        }
        try:
            self.write(json.dumps(result))
        except:
            self.write('status:501'+str(type(resStr)))

def make_app():
    return tornado.web.Application([
        (r"/cut", CutStringHandler),  # 注册路由
        (r"/city_code", CityCodeHandler), # 查询城市代码
        (r"/weather", WeatherHandler) # 查询天气
    ], DEBUG = True)
 
if __name__ == "__main__":
    app = make_app()
    app.listen(8444)
    print("SERVICE RUNNING")
    tornado.ioloop.IOLoop.current().start()
    